const express = require("express");
const http = require("http");
const path = require("path");
const WebSocket = require("ws");
const fs = require("fs");
const multer = require("multer");

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

const PORT = process.env.PORT || 9999;


// 设置静态资源目录，并禁用缓存
app.use(express.static(path.join(__dirname, "public")));

// 设置 dist 文件夹作为静态资源目录
app.use(express.static(path.join(__dirname, "dist")));

// 首页路由
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

// grapes编辑模板
app.get("/grapes", (req, res) => {
  res.sendFile(path.join(__dirname, "grapes.html"));
});

// 设置文件上传中间件
const upload = multer({ dest: path.join(__dirname, "dist") });

// 处理文件上传请求
app.post("/upload", upload.single("htmlFile"), (req, res) => {
  const uploadedFile = req.file;
  const fileName = req.body.fileName; // 从请求体中获取文件名参数
  const extension = req.body.extension; // 从请求体中获取后缀名参数

  if (!uploadedFile || !fileName || !extension) {
    res.status(400).send("Incomplete file information");
    return;
  }

  // 重新命名文件
  const newFileName = `${fileName}.${extension}`;
  fs.renameSync(
    uploadedFile.path,
    path.join(uploadedFile.destination, newFileName)
  );
  console.log('文件上传成功，查看链接：')
  console.log(`http://localhost:${PORT}/${newFileName}`)
  res.send({
    code:200,
    url:`http://localhost:${PORT}/${newFileName}`
  });
});

// WebSocket 服务器逻辑
wss.on("connection", (ws) => {
  console.log("Client connected");

  // 监听静态资源目录中的 index.html 文件的修改
  fs.watch(path.join(__dirname, "index.html"), () => {
    console.log("index.html changed");
    ws.send("reload"); // 发送消息通知客户端重新加载页面
  });

  ws.on("close", () => {
    console.log("Client disconnected");
  });
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`请访问:http://localhost:${PORT}`);
});
